package com.iwuke.dance.wallet.balance;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iwuke.dance.R;
import com.iwuke.dance.activity.BaseActivity;
import com.iwuke.dance.activity.LPWHApplication;
import com.iwuke.dance.gadget_view.TitleBarView;
import com.iwuke.dance.util.ClickableUtil;
import com.iwuke.dance.util.ToastUtil;
import com.iwuke.dance.util.Util;
import com.iwuke.dance.util.independent_edit_text.IndependentEditTextUtil;
import com.iwuke.dance.util.merchants_connect.NetworkEvent;
import com.iwuke.dance.wallet.bean.StarlightValueAndBalanceBean;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * @author: 魏从响
 * @date: 2025/9/26
 * 提现
 */
public class WithdrawActivity extends BaseActivity implements View.OnClickListener {


    private TitleBarView title_bar;
    private TextView tv_nickname;
    private TextView tv_time_desc;
    private EditText et_withdrawal_account;
    private TextView tv_account_desc;
    private TextView tv_withdrawal_all;
    private TextView tv_withdrawal;
    private IWXAPI api;
    private int type;
    private String balance = "0";
    private String starlightValue;


    /**
     * @description 网络实时监听
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(NetworkEvent networkEvent) {
        BaseActivity.setConnect(WithdrawActivity.this, networkEvent, title_bar);
    }

    @Override
    protected int getView() {
        return R.layout.activity_withdraw;
    }

    @Override
    protected void init(View mView) {

        //
        title_bar = findViewById(R.id.title_bar);

        //昵称
        tv_nickname = findViewById(R.id.tv_nickname);
        //到账时间
        tv_time_desc = findViewById(R.id.tv_time_desc);
        //输入金额
        et_withdrawal_account = findViewById(R.id.et_withdrawal_account);
        //可用余额
        tv_account_desc = findViewById(R.id.tv_account_desc);
        //全部提现按钮
        tv_withdrawal_all = findViewById(R.id.tv_withdrawal_all);
        //提现按钮
        tv_withdrawal = findViewById(R.id.tv_withdrawal);


        title_bar.setTitleText("提现");
        title_bar.setLeftOnClick(this);
        //全部提现按钮
        tv_withdrawal_all.setOnClickListener(this);
        //提现按钮
        tv_withdrawal.setOnClickListener(this);

    }

    @Override
    protected void initData() {
        api = ((LPWHApplication) getApplicationContext()).getWxApi();

        StarlightValueAndBalanceBean bean = Util.getSerializableSafe(getIntent(), "data", StarlightValueAndBalanceBean.class);

        type = bean.type;
        if (type==1){//余额提现
            balance = bean.balance;
        }else if (type==2){//星光值提现
            starlightValue = bean.starlightValue;
            balance = Util.setBigDecimal(starlightValue);
        }
        //可用余额
        tv_account_desc.setText("可用余额：¥" + balance);

        //启用数字键盘并允许小数点输入

        et_withdrawal_account.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_withdrawal_account.addTextChangedListener(new TextWatcher() {
            private String current = "";

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().equals(current)) {
                    // 移除监听避免递归
                    et_withdrawal_account.removeTextChangedListener(this);

                    // 1. 删除非数字和小数点的字符
                    String cleanString = s.toString().replaceAll("[^\\d.]", "");

                    // 2. 处理多个小数点
                    if (cleanString.indexOf('.') != cleanString.lastIndexOf('.')) {
                        cleanString = cleanString.substring(0, cleanString.lastIndexOf('.'));
                    }

                    // 3. 限制小数位数
                    if (cleanString.contains(".")) {
                        int decimalIndex = cleanString.indexOf('.');
                        if (cleanString.length() - decimalIndex > 3) { // 限制2位小数
                            cleanString = cleanString.substring(0, decimalIndex + 3);
                        }
                    }

                    // 4. 整数部分不能以0开头（除非是0.x）
                    if (cleanString.startsWith("0") && cleanString.length() > 1
                            && !cleanString.startsWith("0.")) {
                        cleanString = cleanString.substring(1);
                    }

                    current = cleanString;
                    et_withdrawal_account.setText(cleanString);
                    et_withdrawal_account.setSelection(cleanString.length()); // 光标移至末尾

                    // 重新添加监听
                    et_withdrawal_account.addTextChangedListener(this);
                }
            }
        });


    }

    public void loginWithWeChat(String payPassword) {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
        Util.withdrawStart = type;//余额提现
        Util.withdrawAccount = et_withdrawal_account.getText().toString();//提现金额
        Util.password = payPassword;//支付密码
    }

    public void setMemberManagement(Context context) {

        //对于 PopupWindow，正确的做法是在 inflate 时传入 null，但需要确保在创建 PopupWindow 对象时明确指定宽度和高度。你的代码已经做到了这一点，这是关键。
        //因此，消除这个警告最直接有效的方法是在 inflate 方法上使用 @SuppressLint 注解，明确告知编译器你了解这个情况并有意为之：
        @SuppressLint("InflateParams")
        View view = LayoutInflater.from(context).inflate(R.layout.popup_window_password, null);
        PopupWindow popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        //新方法：使用透明的 ColorDrawable   new ColorDrawable(Color.TRANSPARENT)和new BitmapDrawable()一样
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 设置白色背景
        //popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        //创建带圆角的背景 首先，在 res/drawable 目录下创建一个 XML 文件（如 popup_background.xml）：
        //popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.popup_background));
        //使用 NinePatch 图片作为背景 如果你的设计需要更复杂的背景效果，可以使用 .9.png 图片：
        //popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.your_nine_patch_background));
        //设置点击弹窗外隐藏自身
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        //设置位置 在某个控件下面
//        popupWindow.showAsDropDown(tv_search,-10,10);
        //设置位置
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

        view.animate()
                .translationY(-500)
                .setDuration(300)
                .start();

        TextView tv_cancel = view.findViewById(R.id.tv_cancel);//取消
        TextView tv_withdrawal_account = view.findViewById(R.id.tv_withdrawal_account);
        tv_withdrawal_account.setText("¥" + et_withdrawal_account.getText().toString());

        IndependentEditTextUtil independentEditTextUtil = new IndependentEditTextUtil(this, view);
        independentEditTextUtil.setOnEditTextClick(new IndependentEditTextUtil.OnEditTextClick() {
            @Override
            public void onEditTextClick(String value) {
                loginWithWeChat(value);
            }

            @Override
            public void onResendTimeClick() {

            }
        });

        //取消
        tv_cancel.setOnClickListener((v)->{
            popupWindow.dismiss();
        });

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.img_left) {
            finish();
        } else if (v.getId() == R.id.tv_withdrawal_all) {//全部提现按钮
            //输入金额
            et_withdrawal_account.setText(balance);

        } else if (v.getId() == R.id.tv_withdrawal) {//提现按钮
            String string = et_withdrawal_account.getText().toString();
            if (!TextUtils.isEmpty(string)) {
                new ClickableUtil().isClickable(tv_withdrawal);

                setMemberManagement(WithdrawActivity.this);
            } else {
                ToastUtil.setToast(WithdrawActivity.this, "请输入提现金额");
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

}
